﻿using System;
using System.Web.UI;
using CustomerContactSystem.Core.Infrastructure.Configuration;
using CustomerContactSystem.Core.Infrastructure.DataAccess;
using CustomerContactSystem.Core.Model;
using StructureMap;

namespace CustomerContactSystem.WebForms
{
    public partial class Site : MasterPage {
        public IApplicationSettings ConfigSettings { get; set; }
        public INhibernateRepository<User> UserRepository { get; set; }

        private string _userIdSessionKey;
        public string UserIdSessionKey {
            get {
                if (string.IsNullOrEmpty(_userIdSessionKey)) {
                    _userIdSessionKey = ConfigSettings.UserSessionKey;
                }
                return _userIdSessionKey;
            }
        }

        private int _loggedUserId;
        public int LoggedUserId
        {
            get
            {
                if (_loggedUserId == 0)
                {
                    if (Session[UserIdSessionKey] != null) {
                        _loggedUserId = (int)Session[UserIdSessionKey]; 
                    }
                }

                return _loggedUserId;
            }
        }

        private User _loggedUser;
        public User LoggedUser
        {
            get { return _loggedUser ?? (_loggedUser = UserRepository.GetById(LoggedUserId)); }
        }

        protected void Page_Init(object sender, EventArgs e) {
            ObjectFactory.BuildUp(this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (LoggedUserId == 0) {
                CheckIfAnonymousUserRequiresRedirect();
            }
            else
            {
                UserSettingsItem.Visible = true;
                RegisterItem.Visible = false;
                LogInOutLink.NavigateUrl = "~/Logout.ashx";
                LogInOutLink.Text = "Logout";
                StatusItem.Visible = true;
                LoggedInStatus.Text = LoggedUser.DisplayName + " logged in";
                UserSettingsItem.Visible = true;

                if (LoggedUser.IsInRoleLike("Admin"))
                {
                    AdminItem.Visible = true;
                }
            }
            LoadSubMenu();
            //assumes Admin Email is the it support email address - change to suit your circumstances
            ItSupportEmailLink.NavigateUrl = "mailto:" + ConfigSettings.AdminEmailAddress;
            OrganisationName.Text = ConfigSettings.OrganisationNameShort;
        }

        public void AddUserToSession(int userId) {
            Session[UserIdSessionKey] = userId;
        }

        private void LoadSubMenu()
        {
            var currentPath = Request.Path;
            if (currentPath.IndexOf("/Admin/", StringComparison.Ordinal) > -1)
            {
                SecondaryNavigationMenu.Controls.Add(LoadControl("~/SubMenus/AdminMenu.ascx"));
            }
            else if (currentPath.IndexOf("/Customers/", StringComparison.Ordinal) > -1)
            {
                SecondaryNavigationMenu.Controls.Add(LoadControl("~/SubMenus/CustomersMenu.ascx"));
            }
            else if (currentPath.IndexOf("/Enquiries/", StringComparison.Ordinal) > -1 | currentPath.IndexOf("ChangePassword.aspx", StringComparison.Ordinal) > -1)
            {
                SecondaryNavigationMenu.Controls.Add(LoadControl("~/SubMenus/EnquiriesMenu.ascx"));
            }
            else if (currentPath.IndexOf("/Stats/", StringComparison.Ordinal) > -1)
            {
                SecondaryNavigationMenu.Controls.Add(LoadControl("~/SubMenus/StatsMenu.ascx"));
            }
            else
            {
                SecondaryNavigationMenu.Controls.Add(LoadControl("~/SubMenus/LoginMenu.ascx"));
            }
        }

        private void CheckIfAnonymousUserRequiresRedirect()
        {
            if (Request.Path.IndexOf("SettingsCheck.aspx", StringComparison.Ordinal) == -1 & Request.Path.IndexOf("Login.aspx", StringComparison.Ordinal) == -1 & Request.Path.IndexOf("Register.aspx", StringComparison.Ordinal) == -1 & Request.Path.IndexOf("GetLogin.aspx", StringComparison.Ordinal) == -1 & Request.Path.IndexOf("offline.aspx", StringComparison.Ordinal) == -1)
            {
                var qStr = "";
                if ((Request.QueryString.Count > 0))
                {
                    qStr += "&querystring=" + Request.QueryString.ToString().Replace("&", "|").Replace("=", "@");
                }
                Response.Redirect("~/Login.aspx?return=" + Request.Path + qStr);
            }
            else
            {
                LogInOutLink.NavigateUrl = "~/Login.aspx";
                LogInOutLink.Text = "Login";
            }
        }
    }
}